<template>
    <view>
        <van-field :placeholder="placeholder" :size="size" :label="title" :value="picker_data.name" :is-link="isLink" :input-align="inputAlign" readonly  @tap="openPicker">
            <view slot="left-icon">
                <slot name="icon"></slot>
            </view>
        </van-field>
        <van-popup :show="visible" round position="bottom" :z-index="zIndex" @click-overlay="visible = false">
            <van-picker :columns="picker_list" :default-index="current" value-key="name" :show-toolbar="true" @confirm="getPicker" @cancel="visible = false" />
        </van-popup>
    </view>
</template>
<script>
export default {
    props:{
        isLink: {
            type: Boolean,
            default: () => {return true}
        },
        inputAlign:{
            type: String,
            default: () => 'left'
        },
        title: {
            type: String,
        },
        value: {
            type: String || Number
        },
        list: {
            type: Array
        },
        zIndex: {
            type: Number,
            default: () => 100,
        },
        placeholder: {
            type: String,
            default: () => '请选择',
        },
        size: {
            type: String,
            default: () => 'normal'
        }
    },
    data(){
        return{
            visible: false,
        }
    },
    computed:{
        picker_list(){
            return this.list;
        },
        picker_data:{
            get(){
                let obj = this.list.find(item => {
                    return item.id == this.value;
                });
                if(obj){
                    return obj;
                }else{
                    return {};
                }
            },
            set(newVal){
                console.log(newVal);
            }
        },
        current:{
            get(){
                let i = 0;
                this.list.forEach((item,index) => {
                    if(item.id == this.value){
                        i = index;
                    }
                })
                return i;
            },
            set(newVal){
                console.log(newVal);
            }
        }
    },
    methods:{
        openPicker(){
            if(this.picker_list.length > 0){
                this.visible = true;
            }
        },
        getPicker(e){
            const { value, index } = e.detail;
            this.$emit('update:value', value.id);
            this.$emit('confirm', e.detail);
            this.visible = false;
        }
    }
}
</script>